package cn.gjculture.shopping.api.service.impl;

import cn.gjculture.shopping.api.dao.CashCouponDao;
import cn.gjculture.shopping.api.dao.CommonDeleteMapper;
import cn.gjculture.shopping.api.dao.DiscountDao;
import cn.gjculture.shopping.api.dao.DiscountMapper;
import cn.gjculture.shopping.api.entity.Activity;
import cn.gjculture.shopping.api.entity.CashCoupon;
import cn.gjculture.shopping.api.entity.Discount;
import cn.gjculture.shopping.api.service.DiscountService;
import cn.gjculture.shopping.api.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DiscountServiceImpl implements DiscountService {

    @Autowired
    CashCouponDao cashCouponDao;
    @Autowired
    CommonDeleteMapper commonDeleteMapper;

    @Autowired
    DiscountMapper discountMapper;

    @Autowired
    DiscountDao discountDao;

    @Transactional
    @Override
    public int insertDiscounts(Activity activity) {
        List<Discount> discounts=activity.getDiscounts();

        if(discounts!=null&&discounts.size()>0){
            for(Discount dt:discounts){
                dt.setDiscountId(UUIDUtil.getUUID());
                dt.setActivityId(activity.getActivityId());
                if(dt.getDiscountType()==Discount.DiscountType.CASH_COUPON.getValue()){
                    CashCoupon cc=dt.getCashCouponTemplate();
                    cc.setCashCouponId(dt.getDiscountId());
                    cc.setCustomerId(dt.getDiscountId());
                    cashCouponDao.insert(cc);
                }
            }
            discountMapper.insertDiscounts(discounts);
            return discounts.size();
        }
        return 0;
    }

    @Transactional
    @Override
    public List<Discount> getByActivityId(String activityId) {
        List<Discount> discounts= discountDao.queryByActivityId(activityId);
        if(discounts!=null&& discounts.size()>0){
            for(Discount dt:discounts){
                CashCoupon cc=cashCouponDao.queryById(dt.getDiscountId());
                if(cc!=null){
                    dt.setCashCouponTemplate(cc);
                }
            }
            return discounts;
        }
        return null;
    }

    @Transactional
    @Override
    public int deleteByActivitys(List<String> activitys) {
        List<String> discountIds=discountMapper.queryIdsByActivitys(activitys);
        commonDeleteMapper.deleteCashCoupon(discountIds);
        discountMapper.deleteByActivitys(activitys);
        return discountIds.size();
    }

    @Override
    public int deleteByActivity(String activityId) {
        List<String> discountIds=discountDao.queryIdsByActivity(activityId);
        commonDeleteMapper.deleteCashCoupon(discountIds);
        discountDao.deleteByActivityId(activityId);
        return discountIds.size();
    }
}
